package com.puppy.exception;

import com.puppy.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice/*全局异常处理*/
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("服务器发生异常：{}", e.getMessage());
        return Result.error("服务器发生异常~,请联系管理员");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("重复值错误：", e);
        String mesg = e.getMessage(); // 获取异常信息
        int index = mesg.indexOf("Duplicate entry");
        String errorMesg = mesg.substring(index);
        String[] split = errorMesg.split(" ");
        String msg = split[2] + "已存在";
        return Result.error(msg);
    }
}
